const http = require('http').createServer();
const io = require('socket.io')(http);

class Socket {
  constructor() {
    this.io = io;
    this.port = global.option.port;
    this.listen();
  }

  listen() {
    http.listen(this.port, () => {
      console.log(`listen port *:${this.port}`);
    })
  }

  on(name, fn) {
    this.io.on(name, fn);
  }

  emit(name, data, socket, room) {
    let conn = socket || this.io;
    if(room) conn = conn.in(room);
    conn.emit('all', {
      data,
      action: name,
      time: new Date().getTime()
    });
  }

  system(msg, color, socket, room) {
    this.emit('message', {
      msg, color: color || 'red', type: 'system'
    }, socket, room)
  }
}

module.exports = Socket;